using System.Text;
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using Csla.Validation;
using BA.DAL;
using BA;

namespace BlazeApps.Library.Themes
{
    [Serializable()]
    public class ThemeDetail : Csla.BusinessBase<ThemeDetail>
    {
        private BlazeApps.Library.ConfigSettings Config = new BlazeApps.Library.ConfigSettings();
        private BA.DAL.DBUtility DAL = new BA.DAL.DBUtility();
        private Procedures Procs = new Procedures();

        #region Business Properties and Methods

        //declare members
        private Guid _themeid = Guid.NewGuid();
        private string _themename = string.Empty;
        private string _themefolder = string.Empty;
        private int _usagecount = 0;
        private bool _archived = false;

        [System.ComponentModel.DataObjectField(true, false)]
        public Guid Themeid
        {
            get
            {
                CanReadProperty("Themeid", true);
                return _themeid;
            }
            set
            {
                CanWriteProperty("Themeid", true);
                if (!_themeid.Equals(value))
                {
                    _themeid = value;
                    PropertyHasChanged("Themeid");
                }
            }
        }

        public string Themename
        {
            get
            {
                CanReadProperty("Themename", true);
                return _themename;
            }
            set
            {
                CanWriteProperty("Themename", true);
                if (value == null)
                    value = string.Empty;
                if (!_themename.Equals(value))
                {
                    _themename = value;
                    PropertyHasChanged("Themename");
                }
            }
        }

        public string Themefolder
        {
            get
            {
                CanReadProperty("Themefolder", true);
                return _themefolder;
            }
            set
            {
                CanWriteProperty("Themefolder", true);
                if (value == null)
                    value = string.Empty;
                if (!_themefolder.Equals(value))
                {
                    _themefolder = value;
                    PropertyHasChanged("Themefolder");
                }
            }
        }

        public int Usagecount
        {
            get
            {
                CanReadProperty("Usagecount", true);
                return _usagecount;
            }
            set
            {
                CanWriteProperty("Usagecount", true);
                if (!_usagecount.Equals(value))
                {
                    _usagecount = value;
                    PropertyHasChanged("Usagecount");
                }
            }
        }

        public bool Archived
        {
            get
            {
                CanReadProperty("Archived", true);
                return _archived;
            }
            set
            {
                CanWriteProperty("Archived", true);
                if (!_archived.Equals(value))
                {
                    _archived = value;
                    PropertyHasChanged("Archived");
                }
            }
        }

        protected override object GetIdValue()
        {
            return _themeid;
        }

        #endregion //Business Properties and Methods

        #region Validation Rules
        private void AddCustomRules()
        {
            //add custom/non-generated rules here...
        }

        private void AddCommonRules()
        {
            //
            // Themename
            //
            ValidationRules.AddRule(CommonRules.StringRequired, "Themename");
            //
            // Themefolder
            //
            ValidationRules.AddRule(CommonRules.StringRequired, "Themefolder");
        }

        protected override void AddBusinessRules()
        {
            AddCommonRules();
            AddCustomRules();
        }
        #endregion //Validation Rules

        #region Authorization Rules
        protected override void AddAuthorizationRules()
        {
            //TODO: Define authorization rules in ThemeDetail
            //AuthorizationRules.AllowRead("Themeid", "ThemeDetailReadGroup");
            //AuthorizationRules.AllowRead("Themename", "ThemeDetailReadGroup");
            //AuthorizationRules.AllowRead("Themefolder", "ThemeDetailReadGroup");
            //AuthorizationRules.AllowRead("Usagecount", "ThemeDetailReadGroup");
            //AuthorizationRules.AllowRead("Archived", "ThemeDetailReadGroup");

            //AuthorizationRules.AllowWrite("Themename", "ThemeDetailWriteGroup");
            //AuthorizationRules.AllowWrite("Themefolder", "ThemeDetailWriteGroup");
            //AuthorizationRules.AllowWrite("Usagecount", "ThemeDetailWriteGroup");
            //AuthorizationRules.AllowWrite("Archived", "ThemeDetailWriteGroup");
        }


        public static bool CanGetObject()
        {
            //TODO: Define CanGetObject permission in ThemeDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("ThemeDetailViewGroup"))
            //	return true;
            //return false;
        }

        public static bool CanAddObject()
        {
            //TODO: Define CanAddObject permission in ThemeDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("ThemeDetailAddGroup"))
            //	return true;
            //return false;
        }

        public static bool CanEditObject()
        {
            //TODO: Define CanEditObject permission in ThemeDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("ThemeDetailEditGroup"))
            //	return true;
            //return false;
        }

        public static bool CanDeleteObject()
        {
            //TODO: Define CanDeleteObject permission in ThemeDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("ThemeDetailDeleteGroup"))
            //	return true;
            //return false;
        }
        #endregion //Authorization Rules

        #region Factory Methods
        private ThemeDetail()
        { /* require use of factory method */
        }

        public static ThemeDetail NewThemeDetail()
        {
            if (!CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a ThemeDetail");
            return DataPortal.Create<ThemeDetail>();
        }

        public static ThemeDetail GetThemeDetail(Guid themeid)
        {
            if (!CanGetObject())
                throw new System.Security.SecurityException("User not authorized to view a ThemeDetail");
            return DataPortal.Fetch<ThemeDetail>(new Criteria(themeid));
        }

        public static void DeleteThemeDetail(Guid themeid)
        {
            if (!CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a ThemeDetail");
            DataPortal.Delete(new Criteria(themeid));
        }

        public override ThemeDetail Save()
        {
            if (IsDeleted && !CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a ThemeDetail");
            else if (IsNew && !CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a ThemeDetail");
            else if (!CanEditObject())
                throw new System.Security.SecurityException("User not authorized to update a ThemeDetail");

            return base.Save();
        }

        #endregion //Factory Methods

        #region Data Access

        #region Criteria

        [Serializable()]
        private class Criteria
        {
            public Guid Themeid;

            public Criteria(Guid themeid)
            {
                this.Themeid = themeid;
            }
        }

        #endregion //Criteria

        #region Data Access - Create
        [RunLocal]
        protected override void DataPortal_Create()
        {
            ValidationRules.CheckRules();
        }

        #endregion //Data Access - Create

        #region Data Access - Fetch
        private void DataPortal_Fetch(Criteria criteria)
        {
            ExecuteFetch(criteria);
        }

        private void ExecuteFetch(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            DAL.AddParameter("@themeid", criteria.Themeid);

            using(SafeDataReader dr = new SafeDataReader(DAL.ExecuteReader(Procs.GetThemeByThemeID.ToString().Trim(), CommandType.Text, ConnectionState.Open)))
            {
                FetchObject(dr);
                ValidationRules.CheckRules();

                //load child object(s)
                FetchChildren(dr);
            }
        }

        private void FetchObject(SafeDataReader dr)
        {
            dr.Read();
            _themeid = dr.GetGuid("themeid");
            _themename = dr.GetString("themename");
            _themefolder = dr.GetString("themefolder");
            _usagecount = dr.GetInt32("usagecount");
            _archived = dr.GetBoolean("archived");
        }

        private void FetchChildren(SafeDataReader dr)
        {
        }
        #endregion //Data Access - Fetch

        #region Data Access - Insert
        protected override void DataPortal_Insert()
        {
            ExecuteInsert();
        }

        private void ExecuteInsert()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddInsertParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.InsertTheme.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddInsertParameters(ref BA.DAL.DBUtility DAL)
        {
            DAL.AddParameter("@themeid", _themeid);
            DAL.AddParameter("@themename", _themename);
            DAL.AddParameter("@themefolder", _themefolder);
            //if (_usagecount != 0)
            //    DAL.AddParameter("@usagecount", _usagecount);
            //else
            //    DAL.AddParameter("@usagecount", DBNull.Value);
            //if (_archived != false)
            //    DAL.AddParameter("@archived", _archived);
            //else
            //    DAL.AddParameter("@archived", DBNull.Value);
        }
        #endregion //Data Access - Insert

        #region Data Access - Update
        protected override void DataPortal_Update()
        {
            if (base.IsDirty)
            {
                ExecuteUpdate();
            }
        }

        private void ExecuteUpdate()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddUpdateParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.UpdateTheme.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddUpdateParameters(ref BA.DAL.DBUtility DAL)
        {
            DAL.AddParameter("@themeid", _themeid);
            DAL.AddParameter("@themename", _themename);
            DAL.AddParameter("@themefolder", _themefolder);
            //if (_usagecount != 0)
            //    DAL.AddParameter("@usagecount", _usagecount);
            //else
            //    DAL.AddParameter("@usagecount", DBNull.Value);
            //if (_archived != false)
            //    DAL.AddParameter("@archived", _archived);
            //else
            //    DAL.AddParameter("@archived", DBNull.Value);
        }

        private void UpdateChildren(SqlConnection cn)
        {
        }
        #endregion //Data Access - Update

        #region Data Access - Delete
        protected override void DataPortal_DeleteSelf()
        {
            DataPortal_Delete(new Criteria(_themeid));
        }

        private void DataPortal_Delete(Criteria criteria)
        {
            ExecuteDelete(criteria);
        }

        private void ExecuteDelete(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddDeleteParameters(ref DAL, criteria);

            DAL.ExecuteNonQuery(Procs.DeleteTheme.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddDeleteParameters(ref BA.DAL.DBUtility DAL, Criteria criteria)
        {
            DAL.AddParameter("@themeid", criteria.Themeid);
        }
        #endregion //Data Access - Delete
        #endregion //Data Access
    }
}